<template>
  <div class="ant-card">
    <div class="table-page-search-wrapper">
      <a-form-model
        layout="inline"
        :model="searchForm"
        @submit.prevent="fetch"
        ref="searchForm"
      >
        <a-form-model-item label="名称：" prop="name">
          <a-input v-model="searchForm.name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="简写：" prop="shortName">
          <a-input v-model="searchForm.shortName"></a-input>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" html-type="submit">查询</a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="default" @click="resetForm('searchForm')"
            >重置
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="table-operator">
      <a-button
        type="primary"
        html-type="submit"
        @click="showModal('新增角色')"
      >
        新增
      </a-button>
    </div>
    <a-modal
      :title="title"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      width="400px"
    >
      <a-form-model
        layout="horizontal"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 19, offset: 1 }"
        :model="form"
        ref="form"
        :rules="rules"
      >
        <a-form-model-item label="id：" prop="id" v-show="false">
          <a-input v-model="form.id"></a-input>
        </a-form-model-item>
        <a-form-model-item label="名称：" prop="name">
          <a-input v-model="form.name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="简写：" prop="shortName">
          <a-input v-model="form.shortName"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-table
      :dataSource="data"
      rowKey="id"
      bordered
      :pagination="pagination"
      :loading="loading"
    >
      <a-table-column title="id" dataIndex="id" />
      <a-table-column title="名称" dataIndex="name" />
      <a-table-column title="简写" dataIndex="shortName" />
      <a-table-column title="操作" key="action">
        <template v-slot="record">
          <a @click.prevent="edit(record.id)">编辑</a>
          <a-divider type="vertical" />
          <a @click.prevent="del(record.id)">删除</a>
          <a-divider type="vertical" />
          <a @click.prevent="grantResToRole(record.id)">查看或分配资源</a>
        </template>
      </a-table-column>
    </a-table>

    <a-modal
      title="选择资源"
      :visible="dialogFormVisible"
      style="top: 24px;"
      @ok="chooseRes"
      @cancel="cancelChoose"
      :destroyOnClose="true"
      width="600px"
    >
      <resource
        :isDialog="true"
        :resourceIds="resourceIds"
        @get-Resources="getResources"
      ></resource>
    </a-modal>
  </div>
</template>

<script>
import {
  list,
  add,
  getOne,
  del,
  grantResToRole,
  getResIdsByRoleId
} from "@/api/Role";
import Resource from "@/views/sys/Resource";
export default {
  name: "Role",
  data() {
    return {
      //分页
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["10", "20"], //每页中显示的数据
        showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      },
      //封装查询条件
      searchForm: {
        name: null,
        shortName: null
      },
      loading: false,
      //table的数据
      data: [],
      //新增修改模态窗口
      visible: false,

      //模态form
      form: {
        id: null,
        name: null,
        shortName: null
      },
      title: null, //模态窗口 title
      //模态form 校验规则
      rules: {
        name: [{ required: true, message: "不允许为空", trigger: "blur" }],
        shortName: [{ required: true, message: "不允许为空", trigger: "blur" }]
      },

      //分配资源
      dialogFormVisible: false,
      roleId: null,
      resourceIds: [] //接收从子组件传过来的选中资源的id;当前角色拥有的资源
    };
  },
  created() {
    this.fetch();
  },
  components: {
    Resource
  },
  methods: {
    fetch() {
      this.loading = true;
      list(
        this.pagination.current,
        this.pagination.pageSize,
        this.searchForm
      ).then(response => {
        let resp = response.data;
        if (resp.flag) {
          this.data = resp.data.results;
          this.pagination.total = resp.data.totalCount;
        }
        this.loading = false;
      });
    },
    //重置查询表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //模态窗口关闭
    handleCancel() {
      this.visible = false;
    },
    //模态窗口提交按钮:做新增或修改
    handleOk() {
      this.$refs.form.validate(valid => {
        if (valid) {
          add(this.form).then(response => {
            let resp = response.data;
            if (resp.flag) {
              this.$message.success("编辑成功");
              //table重新取最新数据
              this.fetch();
              //隐藏dialog
              this.visible = false;
            } else {
              this.$message.error("编辑失败");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //打开模态窗口
    showModal(title) {
      this.title = title;
      this.visible = true;
      //清空上一次输入
      this.$nextTick(() => {
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        this.$refs["form"].resetFields();
      });
    },
    //修改角色:回显
    edit(id) {
      this.showModal("编辑角色");

      getOne(id).then(response => {
        let resp = response.data;
        if (resp.flag) {
          //给form赋值，必有id
          this.form = resp.data;
        }
      });
    },
    //删除角色
    del(id) {
      this.$confirm({
        title: "提示",
        content: "确定删除吗 ?",
        onOk: () => {
          del(id).then(response => {
            let resp = response.data;
            if (resp.flag) {
              this.fetch();
              this.$message.success("删除成功");
            } else {
              console.log("resp======", resp);
              this.$message.error(`删除失败:${resp.message}`);
            }
          });
        },
        onCancel() {}
      });
    },

    //点确定按钮,给角色授权
    chooseRes() {
      grantResToRole(this.roleId, this.resourceIds).then(response => {
        let resp = response.data;
        if (resp.flag) {
          this.$message.success("角色授资源成功");
          // this.fetch();
          this.dialogFormVisible = false;
        } else {
          this.$message.error("角色授资源失败");
        }
      });
    },
    //取消授权
    cancelChoose() {
      this.dialogFormVisible = false;
    },
    //弹出授权窗口
    grantResToRole(roleId) {
      this.dialogFormVisible = true;
      this.roleId = roleId;

      getResIdsByRoleId(roleId).then(response => {
        let resp = response.data;
        if (resp.flag) {
          console.log("==========resp", resp);
          this.resourceIds = resp.data;
        }
      });
    },

    getResources(data) {
      console.log("从子组件传来的数据:", data);
      this.resourceIds = data;
    }
  }
};
</script>
